<?php
/**
 * 仓库模型
 * @author QiuXiangCheng
 * @date 2016-07-08
 */
class Base_Model_Warehouse extends Model_Base {

	/**
	 * 获取仓库列表
	 * @param array $params
	 * @return string[]
	 */
	/*function getWarehouseList(array $params) {

		$where = ' where 1 ';
		$data = array();
		if (!empty($params['type'])) {
			$where .= " and type=:type";
			$data['type'] = $params['type'];
		}
		if (isset($params['is_oversea']) && $params['is_oversea'] != 404){
			$where .= " and is_oversea=:is_oversea";
			$data['is_oversea'] = $params['is_oversea'];
		}
		if (!empty($params['search_type']) && !empty($params['keyword'])) {
			$where .= " and {$params['search_type']} like :keyword";
			$data['keyword'] = '%'.$params['keyword'].'%';
		}
		if (!empty($params['dept_id'])) {
			if ($params['dept_id'] == 6){
				$where .= " and dept_id is null";
			}else{
				$where .= " and dept_id = :dept_id";
				$data['dept_id'] = $params['dept_id'];
			}
		}
		$sql = "select * from `c_warehouse` ".$where;
		$sql = $sql.' limit '.($params['page'] - 1)*$params['perPage'].','.$params['perPage'];
		$countSql = "select count(1) from `c_warehouse` ".$where;

		$res = array();
		$res['count'] = $this->db()->fetchOne($countSql, $data);
		$res['list']  = $this->db()->fetchAll($sql, $data);

		return $res;
	}*/

	const EXAMINE_GROUP_LEADERS_LEVEL = ['l_leader', 'b_leader', 'director', 'manager'];

	public function getWareDept() {

		$res = $this->db()->fetchPairs("select id, name from `c_warehouse_dept`");
		$res[6] = '其他';
		return $res;
	}

	/**
	 * 通过传输仓库编码取得仓库名称
	 * @param 仓库编码
	 * @return string
	 */
	public static function fetchWarehouseName($wcode) {

		return self::mysql()->fetchAssoc('CALL FETCH_WAREHOUSE_NAME(' . $wcode . ')');
	}

	/**
	 * 取仓库中的数据 用于在列表处显示
	 * param can be where/limit
	 * @param Array(WHERE/LIMIT)
	 */
	public function getWarehouse($param = []) {

		$this->fetchWhereAndLimit($param);
		return $this->db()->fetchAll('SELECT * FROM c_warehouse' . $param['where'] . $param['limit']);
	}

	/**
	 * 通过传输仓库编码取得其事业部
	 * @return interger
	 */
	public static function getDeptIdByWarehouseCode($code) {

		return self::mysql()->fetchOne('SELECT dept_id FROM c_warehouse c WHERE c.warehouse_code = "' . $code . '"');
	}

	/**
	 * where条件和limit过滤
	 * @return string
	 */
	private function fetchWhereAndLimit(&$param) {

		if (isset($param['where'])) {
			if (strlen($param['where']) == 7) {
				$param['where'] = '';
			} else {
				$param['where'] = rtrim($param['where'], 'AND ');
			}
		}
		$param['limit'] = isset($param['limit']) ? $param['limit'] : '';
	}

	/**
	 * 取部门表数量
	 * @return Array
	 */
	public function getCount($params) {

		return $this->db()->fetchOne('SELECT count(*) FROM c_warehouse ' . $params['where']);
	}

	/**
	 * 挑选一些字段取部门表数据
	 * @param 字段（String）
	 * @return Array
	 */
	public function getDepts($fields = 'department_id, department_name, parent_id, status') {

		return $this->db()->fetchAll('SELECT ' . $fields . ' FROM s_department');
	}

	/**
	 * 增加仓库
	 * @param 增加的数据（表里面的字段）
	 */
	public function addWarehouse($data) {

		if ($this->db()->insert('c_warehouse', $data)) {
			return $this->db()->lastInsertId();
		}
		return false;
	}

	/**
	 * 增加审核规则
	 * @param (Intval);
	 */
	public function addWarehouseEx($data) {

		return $this->db()->insert('c_warehouse_ex', $data);
	}

	/**
	 * 表单提交时的检查
	 * @param 表单参数
	 * @return bool/string
	 */
	public function checkFormAdd($data) {

		$param = ['warehouse_name', 'warehouse_code', 'dept_id', 'type', 'auto_send', 'is_oversea', 'special_data_examine', 'special_demand_examine', 'demand_examine', 'comment'];
		foreach ($param as $v) {
			if ($data[$v] == '' || $data[$v] == '-') {
				return $v;
			}
		}
		return 0;
	}

	public static function fetchWarehouseNameByCode() {

		return self::mysql()->fetchAssoc('SELECT warehouse_code, warehouse_name FROM c_warehouse');
	}

	/**
	 * 通过仓库名称检查是否存在该仓库
	 * @return interval
	 */
	public function checkRepeatWarehouseName($warehouseName) {

		return $this->db()->fetchOne('SELECT COUNT(*) COUNT FROM c_warehouse WHERE warehouse_name = "' . $warehouseName . '"');
	}

	/**
	 * 通过仓库代码检测是否存在该仓库
	 * @return interval
	 */
	public function checkRepeatWarehouseCode($warehouseCode) {

		return $this->db()->fetchOne('SELECT COUNT(*) COUNT FROM c_warehouse WHERE warehouse_code = "' . $warehouseCode . '"');
	}

	/**
	 * 根据仓库ID取相关信息
	 * @param 仓库ID
	 * @return Array
	 */
	public function getWarehouseById($did) {

		$where = $did != 0 ? 'WHERE dept_id = ' . $did : '';
		return $this->db()->fetchAll('SELECT id, warehouse_name FROM c_warehouse ' . $where);
	}

	/**
	 * 通过仓库名称取其编码
	 * @param 仓库名称
	 * @return string
	 */
	public static function getWarehouseCodeByWarehouseName($warehouse_name){

		return self::mysql() -> fetchOne('SELECT warehouse_code from c_warehouse WHERE warehouse_name = "' . $warehouse_name . '"');
	}

	/**
	 * 通过传输仓库ID取仓库审核操作记录
	 * @param 仓库ID
	 * @return Array
	 */
	public function getWarehouse_ex($wid = 0) {

		if (is_array($wid)) {
			$where = ' WHERE warehouse_id IN (' . implode(',', $wid) . ')';
		} else if ($wid !== 0) {
			$where = ' WHERE warehouse_id = ' . $wid;
		}
		return $this->db()->fetchAll('SELECT id, auditor, quota, maxnum FROM c_warehouse_ex' . $where);
	}

	public function fetchWarehouseByCode($code) {

		return $this->db()->fetchAssoc('SELECT auditor, id, warehouse_code, quota, maxnum FROM c_warehouse_ex WHERE warehouse_code = "' . $code . '"');
	}

	/**
	 * 删除审核记录
	 * @param 仓库ID
	 * @return Intval
	 */
	public function deleteWarehouse_ex($code = []) {

		return $this->db()->delete('c_warehouse_ex', key($code) . ' in("' . implode('","', $code[key($code)]) . '")');
	}

	/**
	 * 指定取一些字段
	 * @param 字段 默认取所有字段
	 * @return Array();
	 */
	public function getWarehouseFilterFields($fields = '*') {

		return $this->db()->fetchAll('SELECT ' . $fields . ' FROM c_warehouse');
	}

	/**
	 * @param warehouse_id
	 */
	public function getExFromWarhousExById($warehouse_id, $auditor) {

		return $this->db()->fetchAll('SELECT COUNT(*) FROM c_warehouse_ex WHERE warehouse_id = ' . $warehouse_id . ' AND auditor = ' . $auditor);
	}

	/**
	 * 更新仓库审核表（唯一）
	 * 有就替换 没有就增加
	 * @param 表单过来的POST数据
	 * @return boolean
	 */
	public function editWarehouseExamineList($data) {

		if ($data['demand_examine'] == 1) {
			//如果仓库设置需求不需要审核，直接删除审核规则
			return $this->db()->delete('c_warehouse_ex', 'warehouse_code = "' . $data['warehouse_code'] . '"');
		}
		$replace = '';
		foreach (self::EXAMINE_GROUP_LEADERS_LEVEL as $values) {
			if (isset($data[$values]) && isset($data[$values]['auditor'])) {
				$replace .= '(';
				foreach ($data[$values] as $k) {
					if (empty($k)) {
						$k = 0;
					}
					if (!is_numeric($k)) {
						$k = '"' . $k . '"';
					}
					$replace .= $k . ',';
				}
				$replace = rtrim($replace, ',') . '),';
			}
			unset($data[$values]);
		}
		if (!empty($replace)) {
			$this->db()->delete('c_warehouse_ex', 'warehouse_code = "' . $data['warehouse_code'] . '"');
			$replace = 'INSERT INTO c_warehouse_ex (auditor, warehouse_code, quota, maxnum) VALUES ' . rtrim($replace, ',');
			return $this->db()->query($replace);
		}
		return false;
	}

	/**
	 * 批量仓库主页列表审核表（唯一）
	 * @param 数组数据
	 * @return interger
	 */
	public function editWarehouseExamineList_Index($data) {

		$replace = 'REPLACE INTO c_warehouse_ex(warehouse_code, auditor, quota, maxnum) VALUES ';
		foreach ($data['warehouse_code'] as $values) {
			foreach (self::EXAMINE_GROUP_LEADERS_LEVEL as $c) {
				if (isset($data[$c]) && (!empty($data[$c]['quota']) || !empty($data[$c]['maxnum']))) {
					empty($data[$c]['quota']) && $data[$c]['quota'] = 0;
					empty($data[$c]['maxnum']) && $data[$c]['maxnum'] = 0;
					$replace .= '(';
					$replace .= '"' . $values . '",' . implode(',', $data[$c]);
					$replace .= '),';
				}
			}
		}
		return $this->db()->query(rtrim($replace, ','));
	}

	/**
	 * 检查是否已经输入了审核人
	 * @param 表单
	 * @return string/boolean
	 */
	public function checkInputed($data) {

		foreach (self::EXAMINE_GROUP_LEADERS_LEVEL as $values) {
			if (isset($data[$values])) {
				$checking = $data[$values];
				if (!isset($checking['auditor'])) {
					continue;
				}
				if (empty($checking['quota']) && empty($checking['maxnum'])) {
					return '需求审核中：选定了审核人，请填写金额或数量！';
				}
				if (!empty($checking['quota']) && !is_numeric($checking['quota'])) {
					return '需求审核中：金额只能是阿拉伯数字！';
				}
				if (!empty($checking['maxnum']) && !is_numeric($checking['maxnum'])) {
					return '需求审核中：数量只能是阿拉伯数字！';
				}
			}
		}
		return false;
	}

	// 列表中的批量修改
	/*public function editWarehouse_ex_list($data){

		$updated = 0;
		$sql = 'INSERT INTO c_warehouse_ex(id, warehouse_code, auditor, quota, maxnum) VALUES';
		do{
			$key = key($data['warehouse_code']);
			if(!isset($data['warehouse_code'][$key])) break;
			$value = '';
			$duplicate = '';
			foreach($data as $values){
				if(!isset($values['auditor'])) continue;
				$id = !empty($values['id']) ? $values['id'] : 'null';
				$value .= '(' . $id . ',' . $data['warehouse_code'][$key] . ',' . $values['auditor'] . ',' . $values['quota'] . ',' . $values['maxnum'] . '),';
			}
			$duplicate = ' ON DUPLICATE KEY UPDATE id = VALUES(id), warehouse_code = VALUES(warehouse_code), auditor = VALUES(auditor), quota = VALUES(quota), maxnum = VALUES(maxnum)';
			if($this -> db() -> query($sql . rtrim($value, ',') . $duplicate)){
				$updated ++;
			}
			next($data['warehouse_code']);
		}while(1);
		return $updated;
	}*/

	/**
	 * 过滤WHERE条件
	 * @param 引用返回
	 * @param $page 参数
	 * @return null
	 */
	public function filterWhere(&$where, $page) {

		$where = ' WHERE ';
		if (!empty($page['warehouse_code'])) {
			$where .= 'warehouse_code = "' . $page['warehouse_code'] . '" AND ';
		}
		if (!empty($page['comment'])) {
			$where .= 'comment = "' . $page['comment'] . '" AND ';
		}
		if (!empty($page['add_user'])) {
			$where .= 'add_user = "' . $page['add_user'] . '" AND ';
		}
		if (isset($page['dept_id']) && $page['dept_id'] != 0) {
			$where .= 'dept_id = ' . $page['dept_id'] . ' AND ';
		}
		if (isset($page['id']) && $page['id'] != 0) {
			$where .= 'id = ' . $page['id'] . ' AND ';
		}
		if (isset($page['special_data_examine']) && !empty($page['special_data_examine'])) {
			$where .= 'special_data_examine = ' . $page['special_data_examine'] . ' AND ';
		}
		if (isset($page['special_demand_examine']) && $page['special_demand_examine'] != 0) {
			$where .= 'special_demand_examine = ' . $page['special_demand_examine'] . ' AND ';
		}
		if (isset($page['demand_examine']) && $page['demand_examine'] != 0) {
			$where .= 'demand_examine = ' . $page['demand_examine'] . ' AND ';
		}
		$where = rtrim($where, 'AND ');
		if (strlen($where) == 6) {
			$where = '';
		}
	}

	/**
	 * 过滤审核时未选中的角色
	 * @param 数组
	 */
	public function frilterLeader(&$data) {

		if (!isset($data['l_leader']['auditor'])) {
			unset($data['l_leader']);
		}
		if (!isset($data['b_leader']['auditor'])) {
			unset($data['b_leader']);
		}
		if (!isset($data['director']['auditor'])) {
			unset($data['director']);
		}
		if (!isset($data['manager']['auditor'])) {
			unset($data['manager']);
		}
	}

	public function filterGetLeaders(&$get) {

		$arr = [];
		if (isset($get['leader']) && !empty($get['leader']['id'])) {
			$arr[] = $get['leader'];
		}
		if (isset($get['director']) && !empty($get['director']['id'])) {
			$arr[] = $get['director'];
		}
		if (isset($get['manager']) && !empty($get['manager']['id'])) {
			$arr[] = $get['manager'];
		}
		unset($get['leader'], $get['director'], $get['manager']);
		return $arr;
	}

	/**
	 * 根据类型取仓库数据
	 * @return Array
	 */
	public static function fetchPlatformWarehouseName($type = 0, $fields = 'warehouse_code, warehouse_name') {

		if ($type == 0) {
			return self::mysql()->fetchAssoc('SELECT ' . $fields . ' FROM c_warehouse');
		}
		return self::mysql()->fetchAssoc('SELECT ' . $fields . ' FROM c_warehouse WHERE type = "' . $type . '"');
	}

	/**
	 * 批量修改仓库表中的特采需求字段等信息
	 */
	public function editWarehouseForList($data, $idList) {

		return $this->db()->update('c_warehouse', $data, 'warehouse_code IN("' . implode('","', $idList) . '")');
	}

/*	public function editWarehouse_ex($data){

$sql = 'INSERT INTO c_warehouse_ex(id, warehouse_id, auditor, quota, maxnum) VALUES';
$value = '';
$duplicate = '';
// Helper_Array::pr($data);
foreach($data as $values){
if(!isset($values['auditor'])) continue;
$id = !empty($values['id']) ? $values['id'] : 'null';
$value .= '(' . $id . ',' . $data['warehouse_id'] . ',' . $values['auditor'] . ',' . $values['quota'] . ',' . $values['maxnum'] . '),';
}
$duplicate = ' ON DUPLICATE KEY UPDATE id = VALUES(id), warehouse_id = VALUES(warehouse_id), auditor = VALUES(auditor), quota = VALUES(quota), maxnum = VALUES(maxnum)';
return $this -> db() -> query($sql . rtrim($value, ',') . $duplicate);
}*/

	/**
	 * 修改仓库记录
	 * @return intval
	 */
	public function editWarehouse($data) {

		if (isset($data['id'])) {
			$id = $data['id'];
			unset($data['id'], $data['module'], $data['controller'], $data['action']);
		}
		$data['modify_user'] = Model_User::currentLoginUser()->user_name;
		$data['modified'] = date("Y-m-d H:i:s");
		return $this->db()->update('c_warehouse', $data, 'id = ' . $id);
	}
}